﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Data.SqlServerCe;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Collections;
using System.Text.RegularExpressions;

namespace Recipes_6i
{
    public partial class Recipe_Add : UserControl
    {
		private Hashtable selectedIngredients; 
		private DataRow selectedRow;
        private DataTable dtChosenIngredients;

        public Recipe_Add()
        {
            InitializeComponent();
            DataColumn col;
            dtChosenIngredients = new DataTable("dt_ingredients");
            pnl_ingredients.Hide();
            ingredientsTableAdapter.Fill(db_recipes_6iDataSet.ingredients);
			selectedIngredients = new Hashtable();
            // Create first column
            col = new DataColumn("id");
            col.DataType = System.Type.GetType("System.Int32");
            col.ReadOnly = true;
            col.Unique = true;
            dtChosenIngredients.Columns.Add(col);
            dtChosenIngredients.PrimaryKey = new DataColumn[] { col };
            // Create second column
            col = new DataColumn("name");
            col.DataType = System.Type.GetType("System.String");
            col.ReadOnly = true;
            dtChosenIngredients.Columns.Add(col);
            // Create third column
            col = new DataColumn("qty");
            col.DataType = System.Type.GetType("System.Decimal");
            col.ReadOnly = true;
            dtChosenIngredients.Columns.Add(col);
            // Create fourth column
            col = new DataColumn("units");
            col.DataType = System.Type.GetType("System.String");
            col.ReadOnly = true;
            dtChosenIngredients.Columns.Add(col);
            // Create fifth column
            col = new DataColumn("comments");
            col.DataType = System.Type.GetType("System.String");
            col.ReadOnly = true;
            dtChosenIngredients.Columns.Add(col);
            dg_chosenIngredients.DataSource = dtChosenIngredients;
            dg_chosenIngredients.Columns[0].Visible = false; // hide the id column
            dg_chosenIngredients.Columns[2].Width = 30;
            dg_chosenIngredients.Columns[3].Width = 50;
            // capture keypresses
            tb_numServings.KeyPress += new KeyPressEventHandler(tb_numServings_KeyPress);
            tb_qty.KeyPress += new KeyPressEventHandler(tb_qty_KeyPress);
            db_recipes_6iDataSet.ingredients.RowChanged += new DataRowChangeEventHandler(ingredients_RowChanged); // capture rowchange event for ingredients
            ingredientsTableAdapter.Adapter.RowUpdated += new System.Data.SqlServerCe.SqlCeRowUpdatedEventHandler(Adapter_RowUpdated);
            
        }

        void Adapter_RowUpdated(object sender, System.Data.SqlServerCe.SqlCeRowUpdatedEventArgs e)
        {
            //MessageBox.Show("changes have been updateed in db!  (i think)!");
        }

        void ingredients_RowChanged(object sender, DataRowChangeEventArgs e)
        {
            if (e.Action == DataRowAction.Add)
            {

            }
            // make sure dataTable has latest ID #'s   
        }

        void tb_qty_KeyPress(object sender, KeyPressEventArgs e)
        {
            int c = e.KeyChar;
            if (c != 8) // not backspace
            {
                if ((c < 48 || c > 57) && (c != 46)) // not a number or period
                {
                    e.Handled = true;
                }
            }
        }

        void tb_numServings_KeyPress(object sender, KeyPressEventArgs e)
        {
            int c = e.KeyChar;
            if (c != 8) // not backspace
            {
                if ((c < 48 || c > 57) && (c != 46)) // not a number or period
                {
                    e.Handled = true;
                }
            }
        }

        private void cmd_AddIngredient_Click(object sender, EventArgs e)
        {
            pnl_ingredients.Show();
        }

        private void cmd_closeIngredients_Click(object sender, EventArgs e)
        {
            pnl_ingredients.Hide();
        }


        private void gv_ingredients_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {
            //make sure that we don't reference negative index or out of bounds
            if (e.RowIndex >= 0 && e.RowIndex < db_recipes_6iDataSet.ingredients.Count)
            {
                selectedRow = db_recipes_6iDataSet.ingredients[e.RowIndex];
                tb_name.Text = selectedRow["name"].ToString();
                tb_qty.Text = "1";
                //tb_comments.Text = selectedRow[ "comments" ].ToString();
            }
        }

        private void tb_name_TextChanged(object sender, EventArgs e)
        {

        }

		private void cmd_SelectIngredient_Click( object sender, EventArgs e )
		{
            
            DataRow row;
            DataRow r = dtChosenIngredients.NewRow();
            try
            {
                r[0] = selectedRow["ingredientID"];
                r[1] = selectedRow["name"];
                r[2] = Convert.ToDecimal(tb_qty.Text);
                r[3] = selectedRow["defaultUnits"];
                r[4] = tb_comments.Text;
                if (dtChosenIngredients.Rows.Contains(r[0]))
                {
                    MessageBox.Show("Your recipe already includes " + Convert.ToInt32(tb_qty.Text) + " " + selectedRow["defaultUnits"] + "(s)" + " " + selectedRow["name"], "Duplicate Ingredients");
                }
                else
                {
                    dtChosenIngredients.Rows.Add(r);
                    dtChosenIngredients.AcceptChanges();
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("You did not select an ingredient first!");
            }
		}

		private void refreshIngredientList()
		{
            //cb_Ingredients.Items.Clear();

            //for ( int i = 0; i <= selectedIngredients.Count; i++ )
            //{
            //    cb_Ingredients.Items.Add( selectedIngredients[ i ].ToString(), false );
            //}
		}

        private bool validateForm()
        {
            if (tb_recipeName.Text == "")
            {
                tb_recipeName.BackColor = System.Drawing.Color.Yellow;
                return false;
            }
            if (tb_numServings.Text == "")
            {
                tb_numServings.BackColor = System.Drawing.Color.Yellow;
                return false;
            }
            if (tb_prepTime.Text == "")
            {
                tb_prepTime.BackColor = System.Drawing.Color.Yellow;
                return false;
            }
            if (tb_prepInstruct.Text == "")
            {
                tb_prepInstruct.BackColor = System.Drawing.Color.Yellow;
                return false;
            }
            if (tb_cookTime.Text != "")
            {
                if (tb_cookInstruct.Text == "")
                {
                    tb_cookInstruct.BackColor = System.Drawing.Color.Yellow;
                    return false;
                }
            }
            if (dtChosenIngredients.Rows.Count > 0)
            {
                return true;
            }
            else
            {
                MessageBox.Show("You must add at least one ingredient!", "No Ingredients!");
                return false;
            }
            return true;
        }

        private void cmd_saveRecipe_Click(object sender, EventArgs e)
        {
            if (validateForm())
            {
                ////////////////////////////////////////////
                // first add any new rows to the db so we can get the IDS for them
                //      NOT YET IMPLEMENTED
                ////////////////////////////////////////////
                SqlCeConnection conn = new SqlCeConnection("Data Source=db_recipes_6i.sdf");
                SqlCeCommand cmd = new SqlCeCommand(
                    "SELECT MAX(recipeID) FROM recipes", conn);
                conn.Open();
                SqlCeDataReader dr = cmd.ExecuteReader();
                dr.Read();
                int maxCount;
                //maxCount = dr.GetInt32(0);

                maxCount = 0;

                
                dr.Close();
                conn.Close();
                
                for (int i = 0; i < dtChosenIngredients.Rows.Count; i++)
                {
                    DataRow dr1 = db_recipes_6iDataSet.recipes_ingredients.NewRow();
                    dr1["recipeID"] = maxCount + 1; // pulled from database
                    dr1["ingredientID"] = dtChosenIngredients.Rows[i][0];
                    dr1["qty"] = dtChosenIngredients.Rows[i][2];
                    dr1["comments"] = dtChosenIngredients.Rows[i][4];
                    db_recipes_6iDataSet.recipes_ingredients.Rows.Add(dr1);
                    db_recipes_6iDataSet.recipes_ingredients.AcceptChanges();
                }
                DataRow dr2 = db_recipes_6iDataSet.recipes.NewRow();
                dr2["title"] = tb_recipeName.Text;
                dr2["num_servings"] = Convert.ToDecimal(tb_numServings.Text);
                dr2["prep_time"] = tb_prepTime.Text;
                dr2["cook_time"] = tb_cookTime.Text;
                // these are commented out because they were some strange db corruption things happening
                //dr2["prep_instruct"] = tb_prepInstruct.Text;
                //dr2["cook_instruct"] = tb_cookInstruct.Text;
                db_recipes_6iDataSet.recipes.Rows.Add(dr2);
                
                //update the tableadapter
                ingredientsTableAdapter.Update(db_recipes_6iDataSet);
                db_recipes_6iDataSet.recipes.AcceptChanges();
                // title, num_servings, prep_time, cook_time, prep_instruct, cook_instruct
            }
        }

        private void tb_recipeName_TextChanged(object sender, EventArgs e)
        {
            if (tb_recipeName.Text != "")
            {
                tb_recipeName.BackColor = System.Drawing.SystemColors.Window;
            }  
        }

        private void tb_numServings_TextChanged(object sender, EventArgs e)
        {
            if (tb_numServings.Text != "")
            {
                tb_numServings.BackColor = System.Drawing.SystemColors.Window;
            }
        }

        private void tb_prepTime_TextChanged(object sender, EventArgs e)
        {
            if (tb_prepTime.Text != "")
            {
                tb_prepTime.BackColor = System.Drawing.SystemColors.Window;
            }
        }

        private void tb_cookTime_TextChanged(object sender, EventArgs e)
        {
            if (tb_cookTime.Text != "")
            {
                tb_cookTime.BackColor = System.Drawing.SystemColors.Window;
            }
        }

        private void tb_prepInstruct_TextChanged(object sender, EventArgs e)
        {
            if (tb_prepInstruct.Text != "")
            {
                tb_prepInstruct.BackColor = System.Drawing.SystemColors.Window;
            }
        }

        private void tb_cookInstruct_TextChanged(object sender, EventArgs e)
        {
            if (tb_cookInstruct.Text != "")
            {
                tb_cookInstruct.BackColor = System.Drawing.SystemColors.Window;
            }
        }

        private void tb_qty_TextChanged(object sender, EventArgs e)
        {

        }

        private void ingredientsBindingSource_CurrentChanged(object sender, EventArgs e)
        {

        }

        private void cmd_popNew_Click(object sender, EventArgs e)
        {
            pnl_Pop.Visible = true;
        }

        private void cmd_popSubmit_Click(object sender, EventArgs e)
        {
            DataRow row;
            DataRow r = db_recipes_6iDataSet.ingredients.NewingredientsRow();
            r[1] = tb_popName.Text;
            r[2] = tb_popUnit.Text;

            db_recipes_6iDataSet.ingredients.Rows.Add(r);
            ingredientsTableAdapter.Update(db_recipes_6iDataSet.ingredients);
            db_recipes_6iDataSet.ingredients.AcceptChanges();
            ingredientsTableAdapter.Fill(db_recipes_6iDataSet.ingredients);
            pnl_Pop.Visible = false;
        }
    }
}